<?php
define('IN_ADMIN', true);
include("../includes/common.php");
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;

if(!checkRefererHost())exit('{"code":403}');

@header('Content-Type: application/json; charset=UTF-8');

switch($act){
	case 'login':
		if(isset($_POST['user']) && isset($_POST['pass'])){
        
        if(!$_SESSION['pass_error'])$_SESSION['pass_error']=0;
    	$user=daddslashes($_POST['user']);
    	$pass=daddslashes($_POST['pass']);
    	$code=daddslashes($_POST['code']);
    	if (!$code || strtolower($code) != $_SESSION['vc_code']) {
    		unset($_SESSION['vc_code']);
    		json_format(['code'=>'-1','msg'=>'对不起，您输入的验证码错误！']);
    	}elseif($_SESSION['pass_error']>5) {
    		json_format(['code'=>'-1','msg'=>'用户名或密码不正确！']);
    	}elseif($user==$conf['admin_user'] && $pass==$conf['admin_pwd']) {
    		$session=md5($user.$pass.$password_hash);
    		$expiretime=time()+604800;
    		$token=authcode("{$user}\t{$session}\t{$expiretime}", 'ENCODE', SYS_KEY);
    		setcookie("admin_token", $token, time() + 604800);
    		json_format(['code'=>'1','msg'=>'登陆管理中心成功！']);
    	}else {
    		$_SESSION['pass_error']++;
    		json_format(['code'=>'-1','msg'=>'用户名或密码不正确！']);
    	}
    }elseif(isset($_GET['logout'])){
    	if(!checkRefererHost())exit();
    	setcookie("admin_token", "", time() - 604800);
    	json_format(['code'=>'1','msg'=>'您已成功注销本次登陆！']);
    }elseif($islogin==1){
    	json_format(['code'=>'1','msg'=>'您已登录！']);
    }
break;

	case 'getcount':
		$thtime=date("Y-m-d").' 00:00:00';
		$lastday=date("Y-m-d",strtotime("-1 day")).' 00:00:00';
		$count1=$DB->getColumn("SELECT count(*) from pre_file");
		$count2=$DB->getColumn("SELECT count(*) from pre_file WHERE addtime>='$thtime'");
		$count3=$DB->getColumn("SELECT count(*) from pre_file WHERE addtime>='$lastday' AND addtime<'$thtime'");
		$count4=$DB->getColumn("SELECT count(*) from pre_user");

		$result=["code"=>0,"count1"=>$count1,"count2"=>$count2,"count3"=>$count3,"count4"=>$count4];
		exit(json_encode($result));
	break;
	case 'set':
		if(isset($_POST['green_label_porn'])){
			$_POST['green_label_porn'] = implode(',',$_POST['green_label_porn']);
		}
		if(isset($_POST['green_label_terrorism'])){
			$_POST['green_label_terrorism'] = implode(',',$_POST['green_label_terrorism']);
		}
		foreach($_POST as $k=>$v){
			saveSetting($k, $v);
		}
		exit('{"code":0,"msg":"succ"}');
	break;
	case 'iptype':
		$result = [
		['name'=>'0_X_FORWARDED_FOR', 'ip'=>real_ip(0), 'city'=>get_ip_city(real_ip(0))],
		['name'=>'1_X_REAL_IP', 'ip'=>real_ip(1), 'city'=>get_ip_city(real_ip(1))],
		['name'=>'2_REMOTE_ADDR', 'ip'=>real_ip(2), 'city'=>get_ip_city(real_ip(2))]
		];
		exit(json_encode($result));
	break;
	case 'userList':
		if($islogin==1){}else loginmsg('请登录后再操作！');
		$type_arr = ['qq'=>'QQ','wx'=>'微信'];
			if (isset($_GET['kw'])) {
				$kw = daddslashes($_GET['kw']);
				if ($_GET['type'] == 1) {
					$sql = $_GET['method'] == 1 ? " `uid` LIKE '%{$kw}%'" : " `uid`='{$kw}'";
				} elseif ($_GET['type'] == 2) {
					$sql = $_GET['method'] == 1 ? " `nickname` LIKE '%{$kw}%'" : " `nickname`='{$kw}'";
				} else {
					if (filter_var($kw, FILTER_VALIDATE_EMAIL)) {
						$column = 'email';
					} else {
						$column = 'nickname';
					}
					$sql = $_GET['method'] == 1 ? " `{$column}` LIKE '%{$kw}%'" : " `{$column}`='{$kw}'";
				}
			} else {
				$sql = " 1";
			}
			$rs = $DB->query("SELECT * FROM pre_user WHERE {$sql}");
			$data = array();
			while ($res = $rs->fetch()) {
				$data[] = $res;
			}
			
			$count = count($data);
			$limit = isset($_GET['limit']) ? daddslashes($_GET['limit']) : 10;
			$page = isset($_GET['page']) ? daddslashes($_GET['page']) : 1;
			$Total = ($page - 1) * $limit;
			$rs = $DB->query("SELECT * FROM pre_user WHERE {$sql} order by uid desc limit {$Total}, {$limit}");
			while ($res = $rs->fetch()) {
				
				// 获取会员组名称
				$group = $DB->getRow("SELECT * FROM pre_group WHERE id='{$res['group_id']}'");
				$table[] = [
							'uid' => $res['uid'], 
							'type' => $type_arr[$res['type']], 
							'openid' => $res['openid'], 
							'nickname' => $res['nickname'], 
							'faceimg' => $res['faceimg'], 
							'enable' => $res['enable'], 
							'regip' => $res['regip'], 
							'loginip' => $res['loginip'], 
							'group_id' => $group['name'],
							'level' => $res['level'], 
							'addtime' => $res['addtime'], 
							'lasttime' => $res['lasttime']
						];
			}
			json_format(['code' => 0, 'msg' => '数据获取成功！', 'count' => $count, 'data' => $table]);

	break;
	case 'setUserEnable':
		if($islogin==1){}else loginmsg('请登录后再操作！');
			$id=intval($_GET['id']);
			$rows=$DB->getRow("select * from pre_user where uid='{$id}' limit 1");
			if(!$rows){
				json_format(['code' => '-1', 'msg' => '用户不存在！']);
			}
			if($rows['enable'] == '0'){
				if($DB->update('user', ['enable'=>'1'], ['uid'=>$id])) {
					json_format(['code' => '0', 'msg' => '账号已启用！']);
				}else{
					json_format(['code' => '-1', 'msg' => '修改账号启用失败！']);
				}
			}elseif($rows['enable'] == '1'){
				if($DB->update('user', ['enable'=>'0'], ['uid'=>$id])) {
					json_format(['code' => '0', 'msg' => '账号已禁用！']);
				}else{
					json_format(['code' => '-1', 'msg' => '修改账号禁用失败！']);
				}
			}else{
				json_format(['code' => '-1', 'msg' => '未知状态！']);
			}
	break;
	case 'saveUserInfo':
		$id=intval($_GET['id']);
		$level=intval($_GET['level']);
		$rows=$DB->getRow("select * from pre_user where uid='{$id}' limit 1");
		if(!$rows){
			json_format(['code' => '-1', 'msg' => '用户不存在！']);
		}
		if($DB->update('user', ['level'=>$level], ['uid'=>$id])) {
			json_format(['code' => '0', 'msg' => '修改用户等级成功！']);
		}else{
			json_format(['code' => -1, 'msg' => '修改用户等级失败['.$DB->error().']']);
		}
	break;
	case 'delUser':
		$uid=intval($_POST['uid']);
		$row=$DB->getRow("select * from pre_user where uid='$uid' limit 1");
		if(!$row)
			json_format(['code' => -1, 'msg' => '当前用户不存在！']);
		$sql = "DELETE FROM pre_user WHERE uid='$uid'";

		if($DB->exec($sql)) {
				json_format(['code' => 0, 'msg' => '删除用户成功！']);
		}else
			json_format(['code' => -1, 'msg' => '删除用户失败['.$DB->error().']']);
	break;

	// 文件管理
    // 获取资源列表
	case 'fileList':
		if($islogin==1){}else loginmsg('请登录后再操作！');
			if (isset($_GET['kw'])) {
				$kw = daddslashes($_GET['kw']);
				if ($_GET['type'] == 1) {
					$sql = $_GET['method'] == 1 ? " `uid` LIKE '%{$kw}%'" : " `uid`='{$kw}'";
				} elseif ($_GET['type'] == 2) {
					$sql = $_GET['method'] == 1 ? " `nickname` LIKE '%{$kw}%'" : " `nickname`='{$kw}'";
				} else {
					if (filter_var($kw, FILTER_VALIDATE_EMAIL)) {
						$column = 'email';
					} else {
						$column = 'nickname';
					}
					$sql = $_GET['method'] == 1 ? " `{$column}` LIKE '%{$kw}%'" : " `{$column}`='{$kw}'";
				}
			} else {
				$sql = " 1";
			}
			$rs = $DB->query("SELECT * FROM pre_file WHERE {$sql}");
			$data = array();
			while ($res = $rs->fetch()) {
				$data[] = $res;
			}
			
			$count = count($data);
			$limit = isset($_GET['limit']) ? daddslashes($_GET['limit']) : 10;
			$page = isset($_GET['page']) ? daddslashes($_GET['page']) : 1;
			$Total = ($page - 1) * $limit;
			$rs = $DB->query("SELECT * FROM pre_file WHERE {$sql} order by uid desc limit {$Total}, {$limit}");
			while ($res = $rs->fetch()) {
				$pwd_ext2='';
				if(!empty($res['pwd'])){
					$pwd_ext2='&pwd='.$res['pwd'];
				}
				$view = is_view($res['type']);
				$view_type = get_view_type($res['type']);
				$size = size_format($res['size']);

				$fileurl = './down.php/'.$res['hash'].'.'.($res['type']?$res['type']:'file');
				$viewurl = './view.php/'.$res['hash'].'.'.($res['type']?$res['type']:'file');
				$pageurl = './fileck.php?hash='.$res['hash'].$pwd_ext2;

				
				$table[] = [
							'id' => $res['id'], 
							'name' => $res['name'], 
							'type' => $res['type'], 
							'size' => $res['size'], 
							'size2' => size_format($res['size']),
							'hash' => $res['hash'], 
							'addtime' => $res['addtime'], 
							'lasttime' => $res['lasttime'],
							'ip' => $res['ip'], 
							'hide' => $res['hide'], 
							'pwd' => $pwd_ext2, 
							'block' => $res['block'],
							'count' => $res['count'], 
							'uid' => $res['uid'], 
							'view' => $view, 
							'view_type' => $view_type, 
							'fileurl' => $fileurl, 
							'viewurl' => $viewurl, 
							'pageurl' => $pageurl
							
						];
			}
			json_format(['code' => 0, 'msg' => '数据获取成功！', 'count' => $count, 'data' => $table]);
	break;
    // 修改资源状态
	case 'setBlock':
		$id=intval($_GET['id']);
			$rows=$DB->getRow("select * from pre_file where id='{$id}' limit 1");
			if(!$rows){
				json_format(['code' => '-1', 'msg' => '资源不存在！']);
			}
			if($rows['block'] == '0'){
				if($DB->update('file', ['block'=>'1'], ['id'=>$id])) {
					json_format(['code' => '0', 'msg' => '资源已禁用！']);
				}else{
					json_format(['code' => '-1', 'msg' => '修改资源禁用失败！']);
				}
			}elseif($rows['block'] == '1'){
				if($DB->update('file', ['block'=>'0'], ['id'=>$id])) {
					json_format(['code' => '0', 'msg' => '资源已正常！']);
				}else{
					json_format(['code' => '-1', 'msg' => '修改资源正常失败！']);
				}
			}else{
				json_format(['code' => '-1', 'msg' => '未知状态！']);
			}
	break;
    // 修改资源
	case 'editfile':
		$id = intval($_POST['id']);
		$name = trim(htmlspecialchars($_POST['name']));
		$type = trim(htmlspecialchars($_POST['type']));
		$hide = intval($_POST['hide']);
		$ispwd = intval($_POST['ispwd']);
		$pwd = $ispwd==1?trim(htmlspecialchars($_POST['pwd'])):null;
	    
		if(empty($name)){
			json_format(['code' => -1, 'msg' => '文件名不能为空！']);
		}

		if($ispwd==1 && !empty($pwd)){
			if (!preg_match('/^[a-zA-Z0-9]+$/', $pwd)) {
				json_format(['code' => -1, 'msg' => '密码只能由数字和字母组成！']);
			}
		}

		if($DB->update('file', ['name'=>$name, 'type'=>$type, 'hide'=>$hide, 'pwd'=>$pwd], ['id'=>$id])) {
				json_format(['code' => 0, 'msg' => '修改资源成功！']);
		}else{
			json_format(['code' => -1, 'msg' => '修改资源失败['.$DB->error().']']);
		}
	break;
    // 删除资源
	case 'delfile':
		$id=intval($_POST['id']);
		$row=$DB->getRow("select * from pre_file where id='$id' limit 1");
		if(!$row)	
			json_format(['code' => -1, 'msg' => '当前资源不存在！']);
		$DB->delete('file', ['id'=>$id]);
		json_format(['code' => 0, 'msg' => '删除成功！']);
	break;

	// 会员组列表
	case 'group': 
	if($islogin==1){}else loginmsg('请登录后再操作！');
    	if (isset($_GET['kw'])) {
    		$kw = daddslashes($_GET['kw']);
    		if ($_GET['type'] == 1) {
    			$sql = $_GET['method'] == 1 ? " `id` LIKE '%{$kw}%'" : " `id`='{$kw}'";
    		}elseif ($_GET['type'] == 2) {
    			$sql = $_GET['method'] == 1 ? " `name` LIKE '%{$kw}%'" : " `name`='{$kw}'";
    		} else {
    			if (is_numeric($kw)) {
    				$column = 'id';
    			} else {
    				$column = 'name';
    			}
    			$sql = $_GET['method'] == 1 ? " `{$column}` LIKE '%{$kw}%'" : " `{$column}`='{$kw}'";
    		}
    	} else {
    		$sql = " 1";
    	}
    	$rs = $DB->query("SELECT * FROM pre_group WHERE {$sql}");
    	$data = array();
    	while ($res = $rs->fetch()) {
    		$data[] = $res;
    	}
    	$count = count($data);
    	$limit = isset($_GET['limit']) ? daddslashes($_GET['limit']) : 10;
    	$page = isset($_GET['page']) ? daddslashes($_GET['page']) : 1;
    	$Total = ($page - 1) * $limit;
    	$rs = $DB->query("SELECT * FROM pre_group WHERE {$sql} order by id desc limit {$Total}, {$limit}");
    	while ($res = $rs->fetch()) {
    		$table[] = [
    		            'id' => $res['id'], 
    		            'name' => $res['name'], 
    		            'storage_type' => $res['storage_type'],
						'price' => $res['price'],
						'endtime' => $res['endtime'],
						'active' => $res['active']
    		           ];
    	}
    	json_format(['code' => 0, 'msg' => '数据获取成功！', 'count' => $count, 'data' => $table]);
    break;
	// 添加会员组
	case 'addgroup':
		if($islogin==1){}else loginmsg('请登录后再操作！');
		if(isset($_POST['name'])) {
			$name=daddslashes($_POST['name']);
			$storage_type=daddslashes($_POST['storage_type']);
			$price=daddslashes($_POST['price']);
			$endtime=daddslashes($_POST['endtime']);
			$active=daddslashes($_POST['active']);
			if(empty($name)) {
				json_format(['code'=>'-1','msg'=>'会员组名称不可以为空！']);
			}
			if($storage_type == '') {
				json_format(['code'=>'-1','msg'=>'云存储类型不能为空！']);
			}
			$rowname=$DB->getRow("select * from pre_group where name='{$name}' limit 1");
			if($rowname){
				json_format(['code' => '-1', 'msg' => '添加失败，已有同名会员组存在！']);
			}
			if($DB->insert('group', ['name'=>$name, 'storage_type'=>$storage_type, 'price'=>$price, 'endtime'=>$endtime, 'active'=>$active])) {
				json_format(['code'=>'0','msg'=>'恭喜会员组'.$name.'已添加成功！']);
			} else {
				json_format(['code'=>'-1','msg'=>'对不起，本次添加失败，请重试！']);
			}
		} else {
			json_format(['code'=>'-1','msg'=>'对不起，本次添加失败，请重试！']);
		}
	break;
	// 修改会员组
	 case 'editgroup': 
    if($islogin==1){}else loginmsg('请登录后再操作！');
        $id=intval($_POST['id']);
        $row=$DB->getRow("select * from pre_group where id='{$id}' limit 1");
        if(!$row){
            json_format(['code' => '-1', 'msg' => '不存在此条数据！']);
        }
        $name=daddslashes($_POST['name']);
		$storage_type=daddslashes($_POST['storage_type']);
		$price=daddslashes($_POST['price']);
		$endtime=daddslashes($_POST['endtime']);
		$active=daddslashes($_POST['active']);
        if($DB->update('group', ['name'=>$name, 'storage_type'=>$storage_type, 'price'=>$price, 'endtime'=>$endtime, 'active'=>$active], ['id'=>$id])){
                json_format(['code'=>'0','msg'=>'更改会员组为【'.$name.'】成功！']);
            }else{
                json_format(['code'=>'-1','msg'=>'更改会员组为【'.$name.'】失败！原因：<br>'.$DB->error()]);
        }
    break;
	// 删除会员组
	case 'delgroup': 
    if ($islogin == 1) {} else loginmsg('请登录后再操作！');
        $id = intval($_POST['id']);
        $rows = $DB->getRow("SELECT * FROM pre_group WHERE id='{$id}' LIMIT 1");
        if (!$rows) {
            json_format(['code' => '-1', 'msg' => '不存在此条数据！']);
        }
        if($id == '100') {
            json_format(['code' => '-1', 'msg' => '默认组不可删除！']);
        }
        if ($DB->delete('group', ['id'=>$id])) {
            json_format(['code' => '0', 'msg' => '删除会员组【'.$rows['name'].'】成功！']);
        } else {
            json_format(['code' => '-1', 'msg' => '删除会员组【'.$rows['name'].'】失败！']);
        }
    break;
	// 会员组上下架
	case 'switchgroup'://修改会员组状态
		if($islogin==1){}else loginmsg('请登录后再操作！');
			$id=intval($_GET['id']);
			$rows=$DB->getRow("select * from pre_group where id='{$id}' limit 1");
			if(!$rows){
				json_format(['code' => '-1', 'msg' => '当前记录不存在！']);
			}
			if($rows['active'] == '0'){
				if($DB->update('group', ['active'=>'1'], ['id'=>$id])) {
					json_format(['code' => '0', 'msg' => '会员组上架成功！']);
				}else{
					json_format(['code' => '-1', 'msg' => '会员组上架失败！']);
				}
			}elseif($rows['active'] == '1'){
				if($DB->update('group', ['active'=>'0'], ['id'=>$id])) {
					json_format(['code' => '0', 'msg' => '会员组下架成功！']);
				}else{
					json_format(['code' => '-1', 'msg' => '会员组下架失败！']);
				}
			}else{
				json_format(['code' => '-1', 'msg' => '会员组运营状态修改失败！']);
			}
    break;
	//会员组接口列表select
	case 'usergroup':
    if($islogin==1){}else loginmsg('请登录后再操作！');
        $uid = intval($_POST['uid']);
        $group = $DB->query("SELECT * FROM pre_group");
        $userrow = $DB->getRow("SELECT * FROM pre_user WHERE uid = '{$uid}' limit 1");
        $data = '';
        $data .= '<select class="layui-input" name="group" default="'.$userrow['group_id'].'">';
        foreach ($group as $value) {
            $data .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
        }
        $data .= '</select>';
        json_format(['code' => 0, 'data' => $data]);
    break;
	//修改用户组
	case 'edituser':
    if($islogin==1){}else loginmsg('请登录后再操作！');
        $uid=intval($_POST['uid']);
        $rows=$DB->getRow("select * from pre_user where uid='{$uid}' limit 1");
        if(!$rows){
            json_format(['code' => '-1', 'msg' => '当前用户不存在！']);
        }
        $group=daddslashes($_POST['group']);
        if(empty($group)){
            json_format(['code' => '-1', 'msg' => '会员组不能为空！']);
        }
        if($DB->update('user', [ 'group_id'=>$group], ['uid'=>$uid])){
            json_format(['code' => '0', 'msg' => '恭喜您修改用户成功！']);
        } else {
            json_format(['code' => '-1', 'msg' => '修改失败，请重试'.$DB->error()]);
        }
    break;



default:
	exit('{"code":-4,"msg":"No Act"}');
break;
}